package com.zxmr.navigate;

import java.io.IOException;
import java.util.List;

import com.zxmr.action.Request;
import com.zxmr.action.Response;
import com.zxmr.action.ResponsePayload;
import com.zxmr.action.ResultCode;
import com.zxmr.domain.account.AuthorizationByRole;
import com.zxmr.domain.service.AuthorizationService;
import com.zxmr.exception.AuthorizeErrorException;
import com.zxmr.exception.InvalidURLException;

public abstract class Executor {

	URLElement element = null;
	
	public URLElement getElement() {
		return element;
	}

	public void setElement(URLElement element) {
		this.element = element;
	}

	public void internalErrorResponse(Response response)
	{
		ResponsePayload payload = new ResponsePayload("internal error");
		response.setPayload(payload);
		response.setResult(ResultCode.COMPONENT_ERROR);
	}
	public abstract void execute(Request request,Response response);
	public void forward(Request request,Response response,String url)throws AuthorizeErrorException,InvalidURLException
	{
		RequestDispatch.forward(request, response, url);
	}
	public void redirect(Request request,String component)throws ExecuteException
	{
		request.setInternal(true);
		
		try {
			request.send(request.getRequestProperties().getReplyTo(), component);
		} catch (IOException e) {
			throw new ExecuteException("internal error");
		}
		request.setNeedResponse(false);
	}
	public boolean isAuthorized(int user,String action)
	{
		AuthorizationService service = new AuthorizationService();
		List<AuthorizationByRole> abr = service.queryAuthorization(user, action, RequestDispatch.component.getId());

		if(abr == null || abr.isEmpty())
		{
			return false;
		}
		return true;
	}
}
